<?

//Initiate Authenticate
SecurityRedirect ();

//initiate Vars 
define("PRIMARY_KEY","nokwit");
$PRIMARY_KEY    = PRIMARY_KEY;
$PRIMARY_VALUE  = GetParam($PRIMARY_KEY,"");
$FileName       = "ais_transaction_receipt_order.php";
$FileTemplate   = "ais_transaction_receipt_order_form.html";
$SubHeaderTitle = "Transaction Receipt - Order";
$TableName		= "ais_receipt";
$HTMLFormName   = "ReceiptForm";
$MaxGrid        = "100";
$KTRASL		= GetOfficeID();
//$HTMLFormName2  = "BudgetForm";

$FormAction    = $FileName . "?" . AddParam(GetQueryString("QueryString", ""),"form","$HTMLFormName");
$FormEncType   = "application/x-www-form-urlencoded";
//$PMode         = "";

//Initiate Grid Fields;
$FormFields    = array("receipt_id"=>"","urut"=>"0","thbl"=>"","uraian"=>"0","uraian_tools"=>"0","jumlah"=>"number","skada"=>"0","cbm"=>"","jenis"=>"","dol"=>"");

//buildsqlfield ("$TableName", $FormFields);

//Leave Here Untouch
$FormCName     = BuildHTMLField($FormFields,"name",1);
$FormCValue    = BuildHTMLField($FormFields,"value",1);
$SkadaPPN = GetSkadaPPN ();
$SkadaADM = GetSkadaADM ();

//************ FORM ACTION **************
if (trim(GetParam("form",""))==trim($HTMLFormName)) {
	if (GetParam("FormAction","")=="Save") {
		list($FDay,$FMonth,$FYear) = explode("/",GetParam("tglkwit",""));
		$tglkwit = "$FYear-$FMonth-$FDay";
                if (GetParam("duedate","")) {
                    list($FDay,$FMonth,$FYear) = explode("/",GetParam("duedate",""));
                    $duedate = "$FYear-$FMonth-$FDay";
                }

		$rate    = StrToNumber (GetParam("rate",""));

		if (trim(GetParam("nokwit",""))=="AUTO NUMBERED BY SYSTEM")	{
			$ObjNumber  = new autonumber(GetParam("tglkwit",""));
			$TransNo = $ObjNumber->GetNumber("KW");

			FormSave($TableName, "uraian", $FormFields, array("crno"=>GetParam("container_no",""),"ledger"=>GetPeriod(GetParam("tglkwit","")),"debnam"=>GetParam("debnam",""),"nokwit"=>$TransNo,"npwp"=>GetParam("npwp",""),"tglkwit"=>"$tglkwit","remark1"=>GetParam("remark1",""),"remark2"=>GetParam("remark2",""),"remark3"=>GetParam("remark3",""),"duedate"=>$duedate,"nocek"=>GetParam("nocek",""),"curr"=>GetParam("curr",""),"rate"=>$rate,"debtur"=>GetParam("debtur",""),"ktrasl"=>GetOfficeID(),"kdact"=>GetParam("kdact",""),"app1"=>GetParam("app1",""),"nmapp1"=>GetParam("nmapp1","")),"receipt_id");
			if (StrToNumber(GetParam("total_ppn",""))>0) {
				$SQLQuery = "INSERT INTO ais_receipt (uraian,tglkwit,debnam,skada,jumlah,curr,rate,rupiah,debtur,crno,cpid,ledger,ktrasl,nokwit) VALUES ('PPN','".$tglkwit."','".GetParam("debnam","")."','".GetSkadaPPN()."','".StrToNumber(GetParam("total_ppn",""))."','".GetParam("curr","")."','".GetParam("rate","")."','".GetParam("rupiah","")."','".GetParam("debtur","")."','".GetParam("container_no","")."','".GetParam("cpid","")."','".GetPeriod(GetParam("tglkwit",""))."','".GetOfficeID()."','".$TransNo."')";
				$DBConnection->dbc->query($SQLQuery);
			}
			if (StrToNumber(GetParam("total_adm",""))>0) {
				$SQLQuery = "INSERT INTO ais_receipt (uraian,tglkwit,debnam,skada,jumlah,curr,rate,rupiah,debtur,crno,cpid,ledger,ktrasl,nokwit) VALUES ('ADM FEE','".$tglkwit."','".GetParam("debnam","")."','".GetSkadaADM()."','".StrToNumber(GetParam("total_adm",""))."','".GetParam("curr","")."','".GetParam("rate","")."','".GetParam("rupiah","")."','".GetParam("debtur","")."','".GetParam("container_no","")."','".GetParam("cpid","")."','".GetPeriod(GetParam("tglkwit",""))."','".GetOfficeID()."','".$TransNo."')";
				$DBConnection->dbc->query($SQLQuery);
			}

			SetLogActivity($TransNo,"Create","");
    } else {
			$TransNo = GetParam("nokwit","");

			FormSave($TableName, "uraian", $FormFields, array("crno"=>GetParam("container_no",""),"ledger"=>GetPeriod(GetParam("tglkwit","")),"debnam"=>GetParam("debnam",""),"nokwit"=>$TransNo,"npwp"=>GetParam("npwp",""),"tglkwit"=>"$tglkwit","remark1"=>GetParam("remark1",""),"remark2"=>GetParam("remark2",""),"remark3"=>GetParam("remark3",""),"duedate"=>$duedate,"nocek"=>GetParam("nocek",""),"curr"=>GetParam("curr",""),"rate"=>$rate,"debtur"=>GetParam("debtur",""),"ktrasl"=>GetOfficeID(),"kdact"=>GetParam("kdact",""),"app1"=>GetParam("app1",""),"nmapp1"=>GetParam("nmapp1","")),"receipt_id");

			$SQL = "DELETE FROM $TableName WHERE nokwit='".$TransNo."' AND (skada like '$SkadaPPN' OR skada like '$SkadaADM')";
			$DBConnection->dbc->query($SQL);

			if (StrToNumber(GetParam("total_ppn",""))>0) {
				$SQLQuery = "INSERT INTO ais_receipt (uraian,tglkwit,debnam,skada,jumlah,curr,rate,rupiah,debtur,crno,cpid,ledger,ktrasl,nokwit) VALUES ('PPN','".$tglkwit."','".GetParam("debnam","")."','".GetSkadaPPN()."','".StrToNumber(GetParam("total_ppn",""))."','".GetParam("curr","")."','".GetParam("rate","")."','".GetParam("rupiah","")."','".GetParam("debtur","")."','".GetParam("container_no","")."','".GetParam("cpid","")."','".GetPeriod(GetParam("tglkwit",""))."','".GetOfficeID()."','".$TransNo."')";
				$DBConnection->dbc->query($SQLQuery);
			}
			if (StrToNumber(GetParam("total_adm",""))>0) {
				$SQLQuery = "INSERT INTO ais_receipt (uraian,tglkwit,debnam,skada,jumlah,curr,rate,rupiah,debtur,crno,cpid,ledger,ktrasl,nokwit) VALUES ('ADM FEE','".$tglkwit."','".GetParam("debnam","")."','".GetSkadaADM()."','".StrToNumber(GetParam("total_adm",""))."','".GetParam("curr","")."','".GetParam("rate","")."','".GetParam("rupiah","")."','".GetParam("debtur","")."','".GetParam("container_no","")."','".GetParam("cpid","")."','".GetPeriod(GetParam("tglkwit",""))."','".GetOfficeID()."','".$TransNo."')";
				$DBConnection->dbc->query($SQLQuery);
			}

			SetLogActivity($TransNo,"Update","");
		}

		DeleteRecord ("txtCheck",$MaxGrid);
		header("Location: $FileName?PageMode=Form");
		exit;
	}
	if (GetParam("FormAction","")=="Delete") {
//		print "Deleted"."<br>\n";
		FormDelete();
		//SetLogActivity($TransNo,"Delete","");
		//DeleteRecord ("txtCheck",$MaxGrid);
	}
}

//Field Verification 
$Verification  = "False";
$SessionVar    = md5(microtime());
//$SessionVar    = "Stuck";
$VerifyFields = array("nokwit"=>"ID No.","tglkwit"=>"Transaction Date","kdact"=>"Activity Code","curr"=>"Currency");
VerifyHTML ($HTMLFormName,$VerifyFields,$SessionVar,array("debtur"=>"Received From"));

if (GetParam(PRIMARY_KEY,"")) {
	$SQLCount     = "SELECT count(*) FROM `$TableName`";
	$SQLCount    .= "WHERE ".PRIMARY_KEY."='".$PRIMARY_VALUE."' AND not (skada like '$SkadaPPN%' OR skada like '$SkadaADM%')";
	$Count        = $DBConnection->dbc->get_var($SQLCount);	
} else $Count=0;

$NewDataStart = $Count+1;
$InitFunction = "Masking();Masking2();";
$VerifyGrids = array("uraian"=>"0","uraian_tools"=>"0","jumlah"=>"number","skada"=>"");
$Masking1 = BuildMasking ($HTMLFormName,MutatorFields($FormFields,($MaxGrid+$Count)));
$Masking2 = BuildMasking ($HTMLFormName,array("tglkwit"=>"date","rate"=>"number","total_adm"=>"number"),"2");
$JSMasks  = $Masking1.$Masking2;

Init($SessionVar,$JSMasks);
FormGridHTML ($HTMLFormName,$VerifyGrids,$Count,$MaxGrid,$SessionVar);

//************ SET FORM MODE ***************
if (GetParam(PRIMARY_KEY,"")) {  
  $FormMode = "Edit";
  if (!isApproved(GetParam("nokwit",""))) $USER_CANPRINT="";
  else $USER_CANPRINT="1";
} else {
  $FormMode = "Add";
  $USER_CANPRINT="";
}


//******* DATABASE GRID QUERY ***********

$SQL = "SELECT ".BuildFields($FormFields)." FROM `$TableName`";
//Retrieve Parameter from search


if (GetParam(PRIMARY_KEY,"") && $FormMode="Edit") {	
		$SQLPPN   = "SELECT jumlah FROM $TableName WHERE nokwit='".GetParam(PRIMARY_KEY,"")."' AND skada like '$SkadaPPN' ";		
		$TotalPPN = $DBConnection->dbc->get_var($SQLPPN);
		$GrandTotal = $GrandTotal + $TotalPPN;
		if (!$TotalPPN) $TotalPPN="0.00";
		else $TotalPPN=FormatNumber($TotalPPN);

		$SQLADM   = "SELECT jumlah FROM $TableName WHERE nokwit='".GetParam(PRIMARY_KEY,"")."' AND skada like '$SkadaADM' ";		
		$TotalADM = $DBConnection->dbc->get_var($SQLADM);		
		$GrandTotal = $GrandTotal + $TotalADM;
		if (!$TotalADM) $TotalADM="0.00";
		else $TotalADM=FormatNumber($TotalADM);

		$SQLSubTotal = "SELECT sum(jumlah) FROM $TableName WHERE nokwit='".GetParam(PRIMARY_KEY,"")."' AND not (skada like '$SkadaPPN%' OR skada like '$SkadaADM%')";
		$SubTotal = $DBConnection->dbc->get_var($SQLSubTotal);		
		$GrandTotal = $GrandTotal + $SubTotal;
		if (!$SubTotal) $SubTotal="0.00";
		else $SubTotal=FormatNumber($SubTotal);

		if (!$GrandTotal) $GrandTotal="0.00";
		else $GrandTotal=FormatNumber($GrandTotal);

    $SQLGrid  = $SQL."WHERE not (skada like '$SkadaPPN%' OR skada like '$SkadaADM%') AND ".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."'";
    $SQLGrid .= " ORDER BY ".PRIMARY_KEY;
} 





//******* SHOW FORM CONTENT *********
$TBS = new clsTinyButStrong ;
$TBS->LoadTemplate($MOD_TEMPLATE_DIR."/".$FileTemplate);

//********************************* HTML Header ******************************************
//Select Currency Table
$SQLCurr = "SELECT * FROM tblcurrency";
//Select Department:
$SQLDept = "SELECT * FROM tbldept";
//Select Receipt:
$SQLReceipt = "SELECT * FROM tblreceipt";
//Select Activity
$SQLAct  = "SELECT  * FROM tblactivity";


$HeaderFields = array("debnam"=>"0","nokwit"=>"0","npwp"=>"","tglkwit"=>"date","kdact"=>"","remark1"=>"","remark2"=>"","remark3"=>"","payby"=>"","duedate"=>"","nocek"=>"","curr"=>"","rate"=>"number","debtur"=>"","app1"=>"","nmapp1"=>"","crno"=>"");
//Leave Here Untouch
$FormCName     = BuildHTMLField($HeaderFields,"name",1);
$FormCValue    = BuildHTMLField($HeaderFields,"value",1);
$SQLHeader     = "SELECT ".BuildFields($HeaderFields)." FROM $TableName ";

if (GetParam(PRIMARY_KEY,"") && $FormMode="Edit") $SQLHeader .= "WHERE ".PRIMARY_KEY."='".GetParam(PRIMARY_KEY,"")."' AND ktrasl='".GetOfficeID()."'";
$TBS->MergeBlock("currformblk",$DBMysql,$SQLCurr);
$TBS->MergeBlock("actblk",$DBMysql,$SQLAct);
$TBS->MergeBlock("deptblk",$DBMysql,$SQLDept);
$TBS->MergeBlock("receiptblk",$DBMysql,$SQLReceipt);

// HTML Value
$TBS->MergeBlock("headbln",$FormCName);
if (GetParam(PRIMARY_KEY,"")) {$TBS->MergeBlock("headblv",$DBMysql,$SQLHeader);}
else $TBS->MergeBlock("headblv",$FormCValue);



//********************************* HTML GRID *********************************************
//HTML Grid
//print $SQLGrid;
if (strlen($SQLGrid)) $Result = $DBConnection->dbc->get_results($SQLGrid,ARRAY_A);
$Result  = BuildEmptyGrid ($FormFields, $MaxGrid, $Result);

$TBS->MergeBlock("blg",$Result);
$TBS->Show();


//*************** ACTION FUNCTION *******************
function isApproved($nokwit) {
	global $DBConnection,$TableName;
        $SQL = "SELECT app1 FROM $TableName WHERE nokwit='$nokwit' limit 1";
        return $DBConnection->dbc->get_var($SQL);
}

function FormInsert() {
	global $DBConnection,$FileName;
	$DBConnection->Insert();
	header("Location: $FileName?PageMode=Form");
	exit;
}

function FormUpdate() {
	global $DBConnection;
	$DBConnection->Update();
}

function FormDelete() {
	global $DBConnection,$FileName,$TableName;
	$DBConnection->deleteGrid("$TableName",PRIMARY_KEY,PRIMARY_KEY);
	header("Location: $FileName");
	exit;	
}

function FormSearch () {

}

function FormCancel () {
	global $FileName;
	header("Location: ".$FileName);
	exit;
}

function FormSave ($table, $keyField, $FormFields, $SpecialCase="", $PrimaryKey) {
	global $FileName, $MaxGrid, $DBConnection;
	$TotalData = $MaxGrid * 2;	
	$NewDataStart = GetParam("NewData","0");
	for ($a=1;$a<=$TotalData;$a++) {
		foreach ($FormFields as $key=>$formatting) {
			if (!GetParam($keyField.$a,"")) {
				$EndOfData = 1;
				break;
			}
			$value = GetParam($key.$a,"");
			if ($formatting=="number") $value = str_replace(",","",$value);
			if ($formatting=="date") {
				list($day,$month,$year) = explode("/",$value);
				$value = "$year-$month-$day";
		    }
			$DBConnection->add_data($table,$key,addslashes($value));
		}
		$rate = StrToNumber(GetParam("rate",""));
		$jmh  = StrToNumber(GetParam("jumlah".$a,""));
		$rupiah = $rate * $jmh;
		$DBConnection->add_data($table,"rupiah",$rupiah);
		if ($EndOfData) {
			break;
	    }
		if (strlen($SpecialCase)) {
			foreach ($SpecialCase as $key => $value) {
			//	print "add_data($table,$key,$value);<br>";
				$DBConnection->add_data($table,$key,addslashes($value));
			}
		}
//		print "$a < $NewDataStart<br>";
		if ($a < $NewDataStart) {
			 if (strlen($PrimaryKey)) {
			    $DBConnection->UpdateGrid($PrimaryKey,GetParam($PrimaryKey.$a,""));
		 	 } else {
			    $DBConnection->UpdateGrid($keyField,addslashes(GetParam($keyField.$a,"")));
		     }
		} else {
			$DBConnection->InsertGrid();
                        //$DBConnection->dbc->debug();
	    }
	}
}

//*************** USER FUNCTION *******************
function buildsqlfield ($table, $arrayfield) {
		global $DBConnection;
		for ($x=0;$x<count($arrayfield);$x++) {
			$DBConnection->add_htmlfield($table,$arrayfield[$x],GetParam($arrayfield[$x],""));
		}
}

function DeleteRecord ($sequence_name,$PageSize) {
	global $DBConnection,$FileName,$TableName;	
	for ($x=1;$x<=$PageSize;$x++) {				
		if (GetParam($sequence_name.$x,""))	{
			$DBConnection->deleteGrid("$TableName","receipt_id",$sequence_name.$x);
	    }
	}
}

function BuildFields ($FormFields) {
		global $DBConnection;
		$str = "";
		foreach ($FormFields as $key=>$formatting) {
			if (strlen($str)) $str .= ",$key";
			else $str = "$key";
		}
		return $str;
}

function MutatorFields ($FormFields, $MaxGrid) {
		global $DBConnection;
		$array_fields = array();
		for ($x=0;$x<$MaxGrid;$x++) {
			foreach ($FormFields as $key=>$formatting){
				$a=$x+1;
				$array_fields[$key.$a] = "$formatting";
			}			
		}
		return $array_fields;
}
?>